package ingredientsClient;

import java.io.ByteArrayOutputStream;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPFactory;

public class SoapMessage {
    
    private MessageFactory messageFactory;
    private SOAPMessage message;
    
    private SOAPPart soapPart;
    private SOAPEnvelope envelope;
    private SOAPBody body;
            
    public SoapMessage() {
        try
        {
            messageFactory = MessageFactory.newInstance();
            message = messageFactory.createMessage();
            
            soapPart = message.getSOAPPart();
            envelope = soapPart.getEnvelope();
            body = envelope.getBody();
        }
        catch( Exception ex )
        {
            System.err.println( "Error creating message:\n" + ex.toString() );
        }
    }
    
    public void addMethod( SoapMethod method ) throws javax.xml.soap.SOAPException
    {
        body.addChildElement( method.getElement() );
        message.saveChanges();
    }
    
    public String toString()
    {
        try
        {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            message.writeTo( out );
            return out.toString();
         }
        catch( Exception ex )
        {
            System.err.println( "Error creating string:\n" + ex.toString() );
            return "";
        }
    }
    
    public SOAPMessage getMessage()
    {
        return message;
    }
}
